package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.LocalDateTimeUtil;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.serve.domain.NursingProject;
import com.zzyl.serve.dto.ReservationDto;
import com.zzyl.serve.vo.TimeCountVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.ReservationMapper;
import com.zzyl.serve.domain.Reservation;
import com.zzyl.serve.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 预约信息Service业务层处理
 * 
 * @author chenming
 * @date 2025-05-08
 */
@Service
@Slf4j
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService
{
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息
     * 
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询预约信息列表
     * 
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation)
    {
        reservation.setStatus(0);
        reservation.setCreateBy(String.valueOf(UserThreadLocal.getUserId()));
        return save(reservation) ? 1 : 0;
    }

    /**
     * 修改预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        reservation.setUpdateBy(String.valueOf(UserThreadLocal.getUserId()));
        return updateById(reservation) ? 1 : 0;
    }

    /**
     * 批量删除预约信息
     * 
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除预约信息信息
     * 
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 新增预约
     * @param reservationDto
     */
    @Override
    public void addReservation(ReservationDto reservationDto) {
        //设置将reservationDto用copy放到reservation
        Reservation reservation = new Reservation();
        BeanUtils.copyProperties(reservationDto,reservation);

//        reservationDto.setCreateTime(LocalDateTime.now());
        //设置status默认为0
        reservation.setStatus(0);
        reservation.setCreateBy(String.valueOf(UserThreadLocal.getUserId()));
//        reservationMapper.insertReservation(reservation);
//        reservationMapper.addReservation(reservation);
        reservationMapper.insert(reservation);
    }

    /**
     * 分页查询预约信息
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public List<Reservation> getByPage(Integer pageNum, Integer pageSize, Integer status) {
        LambdaQueryWrapper<Reservation> eq = new LambdaQueryWrapper<Reservation>()
                .eq(status != null, Reservation::getStatus, status);
        List<Reservation> reservations = reservationMapper.selectList(eq);
        return reservations;
    }

    /**
     * 查询当前用户当天取消的预约数量
     * @param userId
     * @return
     */
    @Override
    public int getTodayCancelledCount(Long userId) {
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);

        return reservationMapper.countCancelledReservations(userId, startTime, endTime);
    }

    /**
     * 查询每个时间段剩余预约次数
     */
    @Override
    public List<TimeCountVO> getReservationCountByTime(long timestamp) {
        LocalDateTime ldt = LocalDateTimeUtil.of(timestamp);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        /*LocalDateTime ldt = LocalDateTimeUtil.of(timestamp);
        LocalDateTime startTime = LocalDateTimeUtil.startOfDay(ldt);
        LocalDateTime endTime = LocalDateTimeUtil.endOfDay(ldt);*/

        return reservationMapper.countReservationsByTime(startTime, endTime);
    }


    /*@Override
    public void updateReservationStatus() {
        //查询预约时间当天所在最晚时间小于当前时间，则将状态status设置为3(过期)
        LambdaQueryWrapper<Reservation> queryWrapper= Wrappers.lambdaQuery();
        queryWrapper.eq(Reservation::getStatus,0)
                .le(Reservation::getTime,LocalDateTime.now());
        List<Reservation> reservationList = list(queryWrapper);
        if (CollectionUtils.isEmpty(reservationList)){
            return;
        }
        reservationList.forEach(reservation -> {
            reservation.setStatus(3);
            updateById(reservation);
        });
    }*/
    /**
     * 更新预约状态
     */
    @Override
    @Transactional
    public void updateReservationStatus() {
        LocalDateTime now = LocalDateTime.now();

        LocalDateTime todayEnd = now.toLocalDate().atTime(LocalTime.MAX);
        LambdaQueryWrapper<Reservation> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Reservation::getStatus, 0).le(Reservation::getTime, todayEnd);

        List<Reservation> reservationList = list(queryWrapper);
        if (CollectionUtils.isEmpty(reservationList)) {
            log.info("无需要更新的预约记录");
            return;
        }
        reservationList.forEach(reservation -> {
            reservation.setStatus(3);
//            updateById(reservation);
        });

        updateBatchById(reservationList);
        log.info("成功更新 {} 条预约记录为过期状态", reservationList.size());
    }
}
